﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoGear.BLL;
using Entity;
using ECommerce.DAL;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using iTextSharp.text.html;
using iTextSharp.text.xml;
public partial class invoice_quick_print : SitePublicBasePage
{

   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) 
        {
            List<string> idList = new List<string>();
            if (Session["PrintOrderList"] != null)
            {
                //string filepath = Request.PhysicalApplicationPath;
                // string filepath = @"E:\Projets\Polana\autogear-web\pdf\";
                //string[] filePaths = Directory.GetFiles(@"" + Request.PhysicalApplicationPath + "pdf" + " ");
                //foreach (string filePath in filePaths)
                //    File.Delete(filePath);
                //casting line below
                idList = (List<string>)Session["PrintOrderList"];
                rptQuickInvoice.DataSource = idList;
                rptQuickInvoice.DataBind();
            }
            else 
            {
                Response.Redirect(AutoGear.BLL.CustomSiteMap.SalesCCSuccess);
            }
        }
    }

    private ProductPurchaseOrder _order;

    protected void rptQuickInvoice_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string userControl = string.Empty;
                
                //ProductPurchaseOrder order = ProductPurchaseOrder.Load(Convert.ToInt32(e.Item.DataItem.ToString()));
                controls_wucquickInvoice QuickInvoice = (controls_wucquickInvoice)e.Item.FindControl("QuickInvoice");
                controls_wucquickInvoiceWithPrice QuickInvoiceWithPrice = (controls_wucquickInvoiceWithPrice)e.Item.FindControl("QuickInvoiceWithPrice");
                controls_wucQuickInvoiceMultiple QuickInvoiceMulti = (controls_wucQuickInvoiceMultiple)e.Item.FindControl("QuickInvoiceMulti");
                controls_wucquickInvoiceMultipleWithPrice QuickInvoiceMultiWithPrice = (controls_wucquickInvoiceMultipleWithPrice)e.Item.FindControl("QuickInvoiceMultiWithPrice");
                _order = new ProductPurchaseOrder(e.Item.DataItem.ToString());

                if (_order != null)
                {
                    if (_order.IsMultipleShip == false)
                    {
                        Session["count"] = 0;
                        QuickInvoiceMulti.Visible = false;
                        QuickInvoiceMulti.Attributes.CssStyle.Add("display", "none");
                        QuickInvoiceMultiWithPrice.Visible = false;
                        QuickInvoiceMultiWithPrice.Attributes.CssStyle.Add("display", "none");
                        Session["count"] = 0;
                        QuickInvoice.ORDERID = e.Item.DataItem.ToString();
                        QuickInvoiceWithPrice.ORDERID = e.Item.DataItem.ToString();
                       
                    }
                    else
                    {
                        Session["count"] = 0;
                        QuickInvoice.Visible = false;
                        QuickInvoice.Attributes.CssStyle.Add("display","none");
                        QuickInvoiceWithPrice.Visible = false;
                        QuickInvoiceWithPrice.Attributes.CssStyle.Add("display", "none");
                        Session["count"] = 0;
                        QuickInvoiceMulti.ORDERID = e.Item.DataItem.ToString();
                        Session["count"] = 0;
                        QuickInvoiceMultiWithPrice.ORDERID = e.Item.DataItem.ToString();
                        userControl = "QuickInvoiceMulti";
                     
                    }
                }

            }
           
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    
    
    protected void imbPrintInvoice_Click(object sender, EventArgs e)
    {
        //imbPrintInvoice.Visible = false;
        ////PrintInvoice();
        ////List<string> idList = new List<string>();
        ////if (Session["PrintOrderList"] != null)
        ////{
        ////    //casting line below
        ////    idList = (List<string>)Session["PrintOrderList"];
        ////    for (int i = 0; i < idList.Count; i++)
        ////    {
        ////        int orderId =Convert.ToInt32(idList[i].Substring(2));
        ////        ProductPurchaseOrder order = new ProductPurchaseOrder();
        ////        order = ProductPurchaseOrder.Load(orderId);
        ////        order.PrintNo = order.PrintNo + 1;
        ////        order.Update();
        ////    }
           
        ////}

        ////Session["PrintOrderList"] = null;
        ////string url = SiteGlobals.BaseUrl + "pdf/invoice.pdf";
        ////Response.Redirect(url);
        ////ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>window.open('" + url + "')</script>");
        string script = "<script type=\"text/javascript\" language=\"javascript\">window.print();</script>";
        RegisterClientScriptBlock("printscript", script);
    }

    protected void PrintInvoice()
    {   string directory = Request.PhysicalApplicationPath + @"\pdf\";
        string fileName = directory + "invoice.pdf";
        //Marge PDF
        MargePDF(directory, fileName);
    }

    #region ==================================Start Marge PDF=====================================
    private void MargePDF(string directory, string fileName)
    {
        if (string.IsNullOrEmpty(directory)) throw new ArgumentNullException("Folder");
        if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("Destination file");

        // Load all pdf files
        string[] files = Directory.GetFiles(directory, "*.pdf");
        List<byte[]> filesByte = new List<byte[]>();
        foreach (string file in files)
        {
            filesByte.Add(File.ReadAllBytes(file));
        }

        // Call pdf merger
        File.WriteAllBytes(fileName, MergeFiles(filesByte));
    }

    public static byte[] MergeFiles(List<byte[]> sourceFiles)
    {
        Document document = new Document();
        MemoryStream output = new MemoryStream();
        try
        {
            try
            {
                // Initialize pdf writer
                PdfWriter writer = PdfWriter.GetInstance(document, output);
                writer.PageEvent = new PdfPageEvents();

                // Open document to write
                document.Open();
                PdfContentByte content = writer.DirectContent;

                // Iterate through all pdf documents
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    // Create pdf reader
                    PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
                    int numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        // Determine page size for the current page
                        document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
                        // Create page
                        document.NewPage();
                        PdfImportedPage importedPage = writer.GetImportedPage(reader, currentPageIndex);
                        // Determine page orientation
                        int pageOrientation = reader.GetPageRotation(currentPageIndex);
                        if ((pageOrientation == 90) || (pageOrientation == 270))
                        {
                            content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
                        }
                        else
                        {
                            content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("There has an unexpected exception occured during the pdf merging process.", exception);
            }
        }
        finally
        {
            document.Close();
        }
        return output.GetBuffer();
    }

    internal class PdfPageEvents : IPdfPageEvent
    {
        #region members

        private BaseFont _baseFont = null;
        private PdfContentByte _content;

        #endregion

        #region IPdfPageEvent Members

        public void OnOpenDocument(PdfWriter writer, Document document)
        {
            _baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            _content = writer.DirectContent;
        }

        public void OnStartPage(PdfWriter writer, Document document)
        {
        }

        public void OnEndPage(PdfWriter writer, Document document)
        {
            // Write header text
            string headerText = "";
            _content.BeginText();
            _content.SetFontAndSize(_baseFont, 8);
            _content.SetTextMatrix(GetCenterTextPosition(headerText, writer), writer.PageSize.Height - 10);
            _content.ShowText(headerText);
            _content.EndText();

            // Write footer text (page numbers)
            string text = "Page " + writer.PageNumber;
            _content.BeginText();
            _content.SetFontAndSize(_baseFont, 8);
            _content.SetTextMatrix(GetCenterTextPosition(text, writer), 10);
            _content.ShowText(text);
            _content.EndText();
        }

        public void OnCloseDocument(PdfWriter writer, Document document)
        {
        }

        public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition)
        {
        }

        public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition)
        {
        }

        public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
        {
        }

        public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition)
        {
        }

        public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title)
        {
        }

        public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition)
        {
        }

        public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, string text)
        {
        }

        #endregion

        private float GetCenterTextPosition(string text, PdfWriter writer)
        {
            return writer.PageSize.Width / 2 - _baseFont.GetWidthPoint(text, 8) / 2;
        }
    }

    #endregion ===============================End of Marge PDF=====================================
}